package com.openxt.nbzj.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.openxt.nbzj.R;
import com.openxt.nbzj.activity.HomeActivity;
import com.openxt.nbzj.call.AccessStatisticsManager;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.remoting.RemotingEx;
import com.openxt.nbzj.util.SystemUtil;

import butterknife.BindView;
import butterknife.ButterKnife;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016/7/7.
 */
public class SubscriptionFragment extends OpenxtFragment implements View.OnClickListener, RemotingEx.OnActionListener {

    @BindView(R.id.widget)
    LinearLayout widget;
    @BindView(R.id.subscribe_btn)
    RelativeLayout subscribe_btn;

    Context mContext;
    Handler mHandler = new Handler();
    JSONArray dataSource = null;
    RemotingModel remotingModel = null;
    StringBuilder sb = new StringBuilder();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.subscribe, container, false);
        ButterKnife.bind(this, view);

        TextView tv = (TextView) view.findViewById(R.id.openxt_title);
        tv.setText("功能订阅");

        LinearLayout btn = (LinearLayout) view.findViewById(R.id.openxt_title_left);
        btn.setVisibility(View.GONE);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mContext = getActivity();
        remotingModel = new RemotingModel(mContext);
        subscribe_btn.setOnClickListener(this);
    }

    private void initSubscription() {
        try {
            String val = Utils.getLocalStorage(mContext, ConfigModel.LOGIN_NATIVE);
            JSONObject info = JSON.parseObject(val);
            //取住建委用户
            JSONArray CanSubscribe = null;//能订阅部分
            JSONArray Subscribed = null;//已订阅部分
            JSONArray IDENTITIES = info.getJSONArray("IDENTITIES");
            for (int i = 0, j = IDENTITIES.size(); i < j; i++) {
                JSONObject item = IDENTITIES.getJSONObject(i);
                if ("63".equals(item.getString("APPID")) && item.getBooleanValue("ISMR")) {
                    CanSubscribe = item.getJSONArray("CANSUB");
                    Subscribed = item.getJSONArray("SUBED");
                    break;
                }
            }
            if (CanSubscribe == null)
                CanSubscribe = new JSONArray();
            if (Subscribed == null)
                Subscribed = new JSONArray();
            dataSource = new JSONArray();
            for (int i = 0, j = CanSubscribe.size(); i < j; i++) {
                Long ID = CanSubscribe.getLong(i);
                JSONObject item = ConfigModel.getSubscribes(mContext).get(ID);
                if (item == null)
                    continue;
                item = JSON.parseObject(item.toString());
                item.put("Selected", false);
                for (int m = 0, n = Subscribed.size(); m < n; m++) {
                    Long $ID = Subscribed.getLong(m);
                    if (ID.equals($ID)) {
                        item.put("Selected", true);
                        break;
                    }
                }
                dataSource.add(item);
            }

            if (dataSource == null || dataSource.size() == 0)
                return;
            int len = dataSource.size();
            int size = (int) Math.ceil(Double.valueOf(len) / 4);

            widget.removeAllViews();
            LayoutInflater inflater = LayoutInflater.from(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, SystemUtil.dip2Px(80f, mContext), 1.0f);
            for (int i = 0; i < size; i++) {
                LinearLayout l = new LinearLayout(mContext);
                l.setLayoutParams(params);
                l.setOrientation(LinearLayout.HORIZONTAL);
                LinearLayout.LayoutParams _params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
                for (int j = 0; j < 4; j++) {
                    JSONObject item = null;
                    try {
                        item = dataSource.getJSONObject(i * 4 + j);
                    } catch (Exception e) {
                        item = null;
                    }
                    LinearLayout _child = null;
                    if (item == null) {
                        _child = (LinearLayout) inflater.inflate(R.layout.subscribe_item, null);
                        _child.setLayoutParams(_params);
                        ImageView dy = (ImageView) _child.findViewById(R.id.dy);
                        dy.setVisibility(View.GONE);
                        _child.setEnabled(false);
                    } else {
                        String IconURL = item.getString("IconURL");
                        String Name = item.getString("Name");
                        boolean Selected = "true".equals(item.getString("Selected"));
                        _child = (LinearLayout) inflater.inflate(R.layout.subscribe_item, null);
                        _child.setLayoutParams(_params);
                        ImageView item_iv = (ImageView) _child.findViewById(R.id.item_iv);
                        item_iv.setImageBitmap(SystemUtil.getImageFromAssetsFile(IconURL, getActivity()));
                        TextView item_tv = (TextView) _child.findViewById(R.id.item_tv);
                        item_tv.setText(Name);
                        ImageView dy = (ImageView) _child.findViewById(R.id.dy);
                        if (Selected) {
                            dy.setImageResource(R.mipmap.dy_on);
                        } else {
                            dy.setImageResource(R.mipmap.dy);
                        }
                        _child.setTag(item);
                        _child.setOnClickListener(this);
                    }

                    l.addView(_child);
                }
                widget.addView(l);
            }
            widget.invalidate();
        } catch (Exception e) {

        }
    }

    @Override
    public void refresh() {
        AccessStatisticsManager.instance().start(mContext, "#/morder", true);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initSubscription();
            }
        }, 0);
    }

    @Override
    public void willBeDisplayed() {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.subscribe_btn) {
            sb.setLength(0);
            for (int i = 0, j = dataSource.size(); i < j; i++) {
                JSONObject item = dataSource.getJSONObject(i);
                if (item.getBoolean("Selected"))
                    sb.append(item.getString("ID")).append(",");
            }
            if (sb.lastIndexOf(",") != -1)
                sb.deleteCharAt(sb.lastIndexOf(","));
            if (sb.length() == 0) {
                showMsg("请先选择订阅内容");
                return;
            }

            remotingModel.doSbscribeSubmit(this, true, sb.toString());
        } else {
            try {
                JSONObject item = (JSONObject) v.getTag();
                boolean Selected = "true".equals(item.getString("Selected"));
                Selected = !Selected;
                item.put("Selected", Selected);
                ImageView dy = (ImageView) v.findViewById(R.id.dy);
                if (Selected) {
                    dy.setImageResource(R.mipmap.dy_on);
                } else {
                    dy.setImageResource(R.mipmap.dy);
                }
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onActionCompleted(String reVal, String actionName) {
        if ("true".equalsIgnoreCase(reVal)) {
            try {
                String val = Utils.getLocalStorage(mContext, ConfigModel.LOGIN_NATIVE);
                JSONObject info = JSON.parseObject(val);
                JSONArray IDENTITIES = info.getJSONArray("IDENTITIES");
                for (int i = 0, j = IDENTITIES.size(); i < j; i++) {
                    JSONObject item = IDENTITIES.getJSONObject(i);
                    if ("63".equals(item.getString("APPID")) && item.getBooleanValue("ISMR")) {
                        item.put("SUBED", JSON.parseArray("[" + sb.toString() + "]"));
                        break;
                    }
                }
                Utils.setLocalStorage(mContext, ConfigModel.LOGIN_NATIVE, info.toString());
                Utils.setLocalStorage(mContext, ConfigModel.HOME_LOADING, "false");

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ((HomeActivity) getActivity()).setCurrentItem(0);
                    }
                }, 300);
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initSubscription();
            }
        }, 0);
    }
}
